package org.thingsboard.server.transport.mqtt.util;

import com.alibaba.fastjson.JSONObject;
import com.emc.ecs.nfsclient.nfs.NfsCreateMode;
import com.emc.ecs.nfsclient.nfs.NfsSetAttributes;
import com.emc.ecs.nfsclient.nfs.io.Nfs3File;
import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream;
import com.emc.ecs.nfsclient.nfs.io.NfsFileOutputStream;
import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3;
import com.emc.ecs.nfsclient.rpc.CredentialUnix;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;


@Slf4j
public class NfsUtil {


    /*** 上传文件到NFS服务器
     *@parampath NFS 存储的相对路径
     *@paramfileName 文件名称包括文件后缀
     *@paramcontent 文件二进制内容
     *@return

     */

    public static boolean upload(String nfsIp, String nfsDir, String path, String fileName, byte[] content) {

        NfsFileOutputStream outputStream = null;

        NfsSetAttributes nfsSetAttr = new NfsSetAttributes();

//        nfsSetAttr.setMode((long) (0x00100 + 0x00080 + 0x00040 + 0x00020 + 0x00010 + 0x00008 + 0x00004 + 0x00002));
        nfsSetAttr.setMode(0777L);
        try {

            Nfs3 nfs3 = new Nfs3(nfsIp, nfsDir, new CredentialUnix(-2, -2, null), 3);

            String paths[] = path.substring(1).split("/");//去掉第一个/之后进行分割处理

            StringBuilder p = new StringBuilder();//首先判断目录是否存在，如果不存在则进行创建目录
            for (String s : paths) {

                p.append("/").append(s);

                Nfs3File filePath = new Nfs3File(nfs3, p.toString());
                if (!filePath.exists()) {

                    filePath.mkdir(nfsSetAttr);

                }

            }//创建文件
            Nfs3File desFile = new Nfs3File(nfs3, path + "/" + fileName);

            desFile.create(NfsCreateMode.UNCHECKED, nfsSetAttr, null);

            outputStream = new NfsFileOutputStream(desFile);
            outputStream.write(content);
            return true;

        } catch (IOException ex) {
            ex.printStackTrace();
            log.info("nfs服务器连接失败，请求ip--->{},路径---->{}", nfsIp, nfsDir);
        } finally {
            if (null != outputStream) {
                try {

                    outputStream.close();

                } catch (IOException ex) {
                    ex.printStackTrace();
                    log.info("关闭nfs服务连接失败----->{}", ex.getMessage());
                }

            }

        }
        return false;

    }

    /*** 文件下载
     *@paramfilePath NFS上面的文件路径信息
     *@return

     */

    public static byte[] download(String nfsIp, String nfsDir, String filePath) {

        ByteArrayOutputStream bos = null;

        NfsFileInputStream inputStream = null;

        BufferedInputStream bis = null;
        try {

            Nfs3 nfs3 = new Nfs3(nfsIp, nfsDir, new CredentialUnix(-2, -2, null), 3);

            Nfs3File file = new Nfs3File(nfs3, filePath);

            inputStream = new NfsFileInputStream(file);

            bis = new BufferedInputStream(inputStream);

            bos = new ByteArrayOutputStream();
            int date = -1;
            while ((date = bis.read()) != -1) {

                bos.write(date);

            }
            return bos.toByteArray();

        } catch (IOException ex) {
//            Logger.getLogger(NfsUtil.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException();
        } finally {
            if (null != bos) {
                try {

                    bos.close();

                } catch (IOException ex) {

                    Logger.getLogger(NfsUtil.class.getName()).log(Level.SEVERE, null, ex);

                }

            }
            if (null != bis) {
                try {

                    bis.close();

                } catch (IOException ex) {

                    Logger.getLogger(NfsUtil.class.getName()).log(Level.SEVERE, null, ex);

                }

            }
            if (null != inputStream) {
                try {

                    inputStream.close();

                } catch (IOException ex) {

                    Logger.getLogger(NfsUtil.class.getName()).log(Level.SEVERE, null, ex);

                }

            }

        }
//        return null;

    }

    /**
     * 请求截图返回图片信息
     */
    public static byte[] getRequest(String url) {
        log.info("请求的拉流地址----->{}", url);
//        url =  url.replace("\"", "");
//        log.info("请求的拉流地址----->{}", url);
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) {
            String json = EntityUtils.toString(response.getEntity());
            // 解析 JSON 数据
            Map jsonMap = JSONObject.parseObject(json, Map.class);
            String resultJson = String.valueOf(jsonMap.get("result"));
            log.info("拉流请求结果----->{}", jsonMap.get("type"));
            Map resultMap = JSONObject.parseObject(resultJson, Map.class);
            String image = String.valueOf(resultMap.get("image"));
            //图片字符串转byte[]
            byte[] imageBytes = Base64.getDecoder().decode(image);
            return imageBytes;
        } catch (Exception e) {
            log.error("请求截图失败--->{}", e.getMessage());
        }


//        try {
        // 创建 URL 对象
//            URL apiUrl = new URL(url);

        // 创建 HttpURLConnection 对象
//            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
//            connection.setRequestMethod("GET");

        // 获取响应码
//            int responseCode = connection.getResponseCode();
//            System.out.println("Response Code: " + responseCode);
//
//            // 读取响应内容
//            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//            String line;
//            StringBuilder responseContent = new StringBuilder();
//            while ((line = reader.readLine()) != null) {
//                responseContent.append(line);
//            }
//            reader.close();
//            // 断开连接
//            connection.disconnect();
//            InputStream in = connection.getInputStream();
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int length;
//            while ((length = in.read(buffer)) != -1) {
//                out.write(buffer, 0, length);
//            }
//            byte[] imageData = out.toByteArray();
        // 断开连接
//            connection.disconnect();
        // 返回响应内容
//            return imageData;

//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return null;
    }

}

